import React, { useState } from 'react';
import { Button, Form, Input, Select, InputNumber, Upload, Modal, Space, Flex, Radio, Card } from 'antd';
import { PlusOutlined, UploadOutlined, DeleteOutlined } from '@ant-design/icons';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';

const { Option } = Select;

const defaultItem = {
  image: '',
  name: '',
  spec: '',
  brand: '',
  quantity: 1,
  unit: '',
  price: undefined,
};

const PurchaseEntry: React.FC = () => {
  const [form] = Form.useForm();
  const [items, setItems] = useState([{ ...defaultItem }]);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [addForm] = Form.useForm();
  const [showModal, setShowModal] = useState(false);
  const [submitSuccess, setSubmitSuccess] = useState(false);
  const [purchaseType, setPurchaseType] = useState('定向');

  // 图片上传模拟
  const handleUpload = (file: any, idx: number) => {
    const newItems = [...items];
    newItems[idx].image = URL.createObjectURL(file);
    setItems(newItems);
    return false;
  };

  const handleAddItem = (values: typeof defaultItem) => {
    setItems([...items, { ...values }]);
    setAddModalVisible(false);
    addForm.resetFields();
  };

  const handleRemoveItem = (idx: number) => {
    if (items.length === 1) return;
    setItems(items.filter((_, i) => i !== idx));
  };

  const handleItemChange = (idx: number, key: string, value: any) => {
    const newItems: any[] = [...items];
    newItems[idx][key] = value;
    setItems(newItems);
  };

  const handleFinish = (values: any) => {
    setShowModal(true);
  };

  const handleModalOk = () => {
    setShowModal(false);
    setSubmitSuccess(true);
    setTimeout(() => setSubmitSuccess(false), 2000);
    form.resetFields();
    setItems([{ ...defaultItem }]);
  };

  return (
    <PageContainer>
      <Form
        form={form}
        layout="vertical"
        onFinish={handleFinish}
        initialValues={{ purchaseType: '定向', org: '', priceType: '市场价' }}
      >
        {items.map((item, idx) => (
          <Card
            key={idx}
            style={{ marginBottom: 16 }}
            title={`物品${idx + 1}`}
            extra={
              items.length > 1 ? (
                <Button danger size="small" icon={<DeleteOutlined />} onClick={() => handleRemoveItem(idx)} />
              ) : null
            }
          >
            <Space align="start" size="large">
              <Flex justify="space-between">
                {item.image ? (
                  <img src={item.image} alt="商品" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4 }} />
                ) : (
                  <div style={{ width: 80, height: 80, background: '#f5f5f5', borderRadius: 4, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#aaa' }}>无图片</div>
                )}
                <Flex vertical align="center" justify="space-between" style={{ padding: 32 }}>
                  <ProDescriptions
                    column={2}
                    bordered
                    size="middle"
                    dataSource={item}
                    columns={[
                      { title: '名称', dataIndex: 'name' },
                      { title: '规格', dataIndex: 'spec' },
                      { title: '品牌', dataIndex: 'brand' },
                      { title: '数量', dataIndex: 'quantity' },
                      { title: '单位', dataIndex: 'unit' },
                      { title: '单价', dataIndex: 'price', render: (_, record) => record.price !== undefined ? record.price : '-' },
                    ]}
                  />
                </Flex>
              </Flex>

            </Space>
          </Card>
        ))}
        <Form.Item>
          <Button type="dashed" block icon={<PlusOutlined />} onClick={() => setAddModalVisible(true)}>
            添加物品
          </Button>
        </Form.Item>
        <Modal
          open={addModalVisible}
          title="添加物品"
          onCancel={() => setAddModalVisible(false)}
          footer={null}
        >
          <Form
            form={addForm}
            layout="vertical"
            onFinish={handleAddItem}
            initialValues={{ ...defaultItem }}
          >
            <Form.Item label="商品图片" name="image">
              <Upload
                beforeUpload={file => {
                  addForm.setFieldsValue({ image: URL.createObjectURL(file) });
                  return false;
                }}
                showUploadList={false}
              >
                <Button icon={<UploadOutlined />}>上传图片</Button>
              </Upload>
              {addForm.getFieldValue('image') && (
                <img src={addForm.getFieldValue('image')} alt="商品" style={{ width: 80, height: 80, objectFit: 'cover', borderRadius: 4, marginTop: 8 }} />
              )}
            </Form.Item>
            <Form.Item label="商品名称" name="name" rules={[{ required: true, message: '请输入商品名称' }]}>
              <Input maxLength={20} placeholder="请输入商品名称" />
            </Form.Item>
            <Form.Item label="商品规格" name="spec" rules={[{ required: true, message: '请输入商品规格' }]}>
              <Input maxLength={20} placeholder="如：A4-100页" />
            </Form.Item>
            <Form.Item label="商品品牌" name="brand">
              <Input maxLength={20} placeholder="请输入品牌" />
            </Form.Item>
            <Form.Item label="数量" name="quantity" rules={[{ required: true, message: '请输入数量' }]}>
              <InputNumber min={1} max={999} style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item label="单位" name="unit" rules={[{ required: true, message: '请选择单位' }]}>
              <Select placeholder="请选择单位">
                <Option value="本">本</Option>
                <Option value="个">个</Option>
                <Option value="箱">箱</Option>
                <Option value="包">包</Option>
                <Option value="件">件</Option>
              </Select>
            </Form.Item>
            <Form.Item label="采购单价(元)" name="price" rules={[{ required: true, message: '请输入单价' }]}>
              <InputNumber min={0} max={999999} style={{ width: '100%' }} placeholder="请输入单价" />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button onClick={() => setAddModalVisible(false)}>取消</Button>
                <Button type="primary" htmlType="submit">添加</Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
        <Form.Item label="采购类型" name="purchaseType" required>
          <Radio.Group onChange={e => setPurchaseType(e.target.value)}>
            <Radio value="定向">定向</Radio>
            <Radio value="申领">申领</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="申购单位" name="org" required>
          <Select placeholder="请选择申购单位">
            <Option value="部门A">部门A</Option>
            <Option value="部门B">部门B</Option>
            <Option value="部门C">部门C</Option>
          </Select>
        </Form.Item>
        <Form.Item label="采购价格类型" name="priceType" required>
          <Select>
            <Option value="市场价">市场价</Option>
            <Option value="协议价">协议价</Option>
          </Select>
        </Form.Item>
        <Form.Item>
          <Space>
            <Button htmlType="button" onClick={() => form.resetFields()}>重置</Button>
            <Button type="primary" htmlType="submit">提交采购单</Button>
          </Space>
        </Form.Item>
      </Form>
      <Modal
        open={showModal}
        onOk={handleModalOk}
        onCancel={() => setShowModal(false)}
        footer={[
          <Button key="ok" type="primary" onClick={handleModalOk}>好的</Button>,
        ]}
      >
        <div style={{ textAlign: 'center', padding: 24 }}>
          <h3>提交成功</h3>
          <div>采购信息已提交，相关人员会尽快审核！</div>
        </div>
      </Modal>
      <Modal
        open={submitSuccess}
        footer={null}
        closable={false}
        onCancel={() => setSubmitSuccess(false)}
      >
        <div style={{ textAlign: 'center', padding: 24 }}>
          <h3>提交成功</h3>
        </div>
      </Modal>
    </PageContainer>
  );
};

export default PurchaseEntry;
